<?php

class UserController extends RController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function filters()
		{
			return array(
			 'rights', // perform access control for CRUD operations
		);
	}
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	public function actionListarAdmin()
		{
			$admin=new Administrador('search');
			$admin->unsetAttributes();  // Limpiamos los valores de busqueda
			$admin->findAll();
			if(isset($_GET['Administrador']))
				$admin->attributes=$_GET['Administrador'];
			$this->render('listarAdmin',array(
				'admin'=>$admin,
			));
		}

	public function actionListarAdminis()
		{
			$admin=new Administrativo('search');
			$admin->unsetAttributes();  // Limpiamos los valores de busqueda
			$admin->findAll();
			if(isset($_GET['Administrativo']))
				$admin->attributes=$_GET['Administrativo'];
			$this->render('listarAdminis',array(
				'admin'=>$admin,
			));
		}
	
	public function actionListarProfes(){
		$profe=new Profesor('search');
		$profe->unsetAttributes();
		$profe->findAll();
		if(isset($_GET['Profesor']))
			$profe->attributes=$_GET['Profesor'];
		$this->render('listarProfes',array(
			'profe'=>$profe,		
		));
	}
		
	public function actionListarCuentasDesactivadas()
		{
			$model=new User('buscarDesactivados');
			$model->unsetAttributes();
			$model->findAll();
			if(isset($_GET['User']))
			$model->attributes=$_GET['User'];
			$this->render('listarDesactivados',array(
								'model'=>$model,
			));
		
		}

	public function actionModificarAdministrador($id){
		$admin = new Administrador();
		$admin =  Administrador::model()->findByPk($id);
		if($admin!=null){
			$model=$this->loadModel($admin->user_id);
			// Uncomment the following line if AJAX validation is needed
			// $this->performAjaxValidation($model);
			if(isset($_POST['User'],$_POST['Administrador']))
			{
				$model->attributes=$_POST['User'];
				$admin->attributes=$_POST['Administrador'];
				$modeloValido=$model->validate();
				$modeloAdministrador=$admin->validate();
				if($modeloValido && $modeloAdministrador){
						$model->password=md5($model->password);
						$model->save(false);
						$admin->user_id=$model->id;
						$admin->save(false);
						$this->redirect(array('verAdministrador','id'=>$admin->idadministrador));
				}
			}
			$this->render('modificarAdministrador',array(
						'model'=>$model,
						'admin'=>$admin,
			));
		}
		else
			throw new CHttpException(404,'La página solicitada no existe.');
	}

	public function actionModificarAdministrativo($id){
		$admin = new Administrativo();
		$admin =  Administrativo::model()->findByPk($id);
		if($admin!=null){
			$model=$this->loadModel($admin->user_id);
			// Uncomment the following line if AJAX validation is needed
			// $this->performAjaxValidation($model);
			if(isset($_POST['User'],$_POST['Administrativo']))
			{
				$model->attributes=$_POST['User'];
				
				$admin->attributes=$_POST['Administrativo'];
				$modeloValido=$model->validate();
				$modeloAdministrador=$admin->validate();
				if($modeloValido && $modeloAdministrador){
					$model->password=md5($model->password);
					$model->save(false);
					$admin->user_id=$model->id;
					$admin->save(false);
					$this->redirect(array('verAdministrativo','id'=>$admin->idadministrativo));
				}
			}
			$this->render('modificarAdministrativo',array(
						'model'=>$model,
						'admin'=>$admin,
			));
		}
		else
			throw new CHttpException(404,'La página solicitada no existe.');
	}	
	
	public function actionModificarProfesor($id){
		$profe = new Profesor();
		$profe =  Profesor::model()->findByPk($id);
		if($profe!=null){	
			$model=$this->loadModel($profe->user_id);
			// Uncomment the following line if AJAX validation is needed
			// $this->performAjaxValidation($model);
			if(isset($_POST['User'],$_POST['Profesor']))
			{
				$model->attributes=$_POST['User'];
				
				$profe->attributes=$_POST['Profesor'];
				$modeloValido=$model->validate();
				$modeloProfesor=$profe->validate();
				if($modeloValido && $modeloProfesor){
					$model->password=md5($model->password);
					$model->save(false);
					$profe->user_id=$model->id;
					$profe->save(false);
					$this->redirect(array('verProfesor','id'=>$profe->idprofesor));
				}
			}
			$this->render('modificarProfesor',array(
							'model'=>$model,
							'profe'=>$profe,
			));
		}
		else
			throw new CHttpException(404,'La página solicitada no existe.');
	}
	public function actionDesactivarCuenta($id){
		if(Yii::app()->request->isPostRequest)
		{
			$user = new User();
			$user=$this->loadModel($id);
			if($user!=null){
				$user->activo=0;
				$user->save();
				if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
			}
			else
			throw new CHttpException(404,'Solicitud inválida usuario no encontrado.');
		}
		else
		throw new CHttpException(404,'Solicitud inválida.');
	}
	
	public function actionReactivar($id){
		$model=$this->loadModel($id);
		if($model!=null){
			$model->activo=1;
			$model->save();
			$this->redirect(array('listarCuentasDesactivadas'));
		}
		else
			throw new CHttpException(404,'La página solicitada no existe.');
	}
	
	public function actionVerAdministrador($id)
	{
		$admin = new Administrador();
		$admin=Administrador::model()->find("idadministrador=".$id);
		if($admin!=null){
			$this->render('verAdministrador',array(
							'model'=>$this->loadModel($admin->user_id),
							'admin'=>$admin,
			));
		}
		else
			throw new CHttpException(404,'La página solicitada no existe.');
	}
	
	public function actionVerAdministrativo($id)
	{
		$admin = new Administrativo();
		$admin=Administrativo::model()->find("idadministrativo=".$id);
		if($admin!=null){
			$this->render('verAdministrativo',array(
								'model'=>$this->loadModel($admin->user_id),
								'admin'=>$admin,
			));
		}
		else
			throw new CHttpException(404,'La página solicitada no existe.');
	}
	
	public function actionVerProfesor($id)
	{
		$profe = new Profesor();
		$profe=Profesor::model()->find("idprofesor=".$id);
		if($profe!=null){
			$this->render('verProfesor',array(
									'model'=>$this->loadModel($profe->user_id),
									'profe'=>$profe,
			));
		}
		else
			throw new CHttpException(404,'La página solicitada no existe.');
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	
	
	public function actionCrearAdministrador()
	{
		$model=new User;
		$admin=new Administrador;
	
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
	
		if(isset($_POST['User'],$_POST['Administrador']))
		{
			$model->attributes=$_POST['User'];
			$admin->attributes=$_POST['Administrador'];
			$model->foto=CUploadedFile::getInstance($model, 'foto');
			$modeloValido=$model->validate();
			$modeloAdministrador=$admin->validate();
			if($modeloValido && $modeloAdministrador){
				$model->password=md5($model->password);
				if(isset($model->foto) && $model->foto->error==0){
					$foto_src='/images/user'.'/'.$model->username.'/'.$model->username.'.'.$model->foto->extensionName;
					$model->setAttribute('foto_src', $foto_src);
				}
				$model->save(false);
				if(isset($model->foto) && $model->foto->error==0){
					$carpeta=Yii::getPathOfAlias('webroot.images.user');
					if(!is_dir($carpeta.'/'.$model->username)){
						mkdir($carpeta.'/'.$model->username);
					}
					$carpeta=$carpeta.'/'.$model->username;
					$model->foto->saveAs($carpeta.'/'.$model->username.'.'.$model->foto->extensionName);
				}
				$admin->user_id=$model->id;
				$admin->save(false);
				Rights::assign('Administrador', $model->id);
				$this->redirect(array('verAdministrador','id'=>$admin->idadministrador));
			}
			
			/*if($model->save())
			$this->redirect(array('view','id'=>$model->id));*/
		}
	
		$this->render('crearAdministrador',array(
				'model'=>$model,
				'admin'=>$admin,
		));
	}
	
	public function actionCrearAdministrativo()
	{
		$model=new User;
		$admin=new Administrativo;
	
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
	
		if(isset($_POST['User'],$_POST['Administrativo']))
		{
			$model->attributes=$_POST['User'];
			$admin->attributes=$_POST['Administrativo'];
			$model->foto=CUploadedFile::getInstance($model, 'foto');
			$modeloValido=$model->validate();
			$modeloAdministrador=$admin->validate();
			if($modeloValido && $modeloAdministrador){
				$model->password=md5($model->password);
				if(isset($model->foto) && $model->foto->error==0){
					$foto_src='/images/user'.'/'.$model->username.'/'.$model->username.'.'.$model->foto->extensionName;
					$model->setAttribute('foto_src', $foto_src);
				}
				$model->save(false);
				if(isset($model->foto) && $model->foto->error==0){
					$carpeta=Yii::getPathOfAlias('webroot.images.user');
					if(!is_dir($carpeta.'/'.$model->username)){
						mkdir($carpeta.'/'.$model->username);
					}
					$carpeta=$carpeta.'/'.$model->username;
					$model->foto->saveAs($carpeta.'/'.$model->username.'.'.$model->foto->extensionName);
				}
				$admin->user_id=$model->id;
				$admin->save(false);
				Rights::assign('Administrativo', $model->id);
				$this->redirect(array('verAdministrativo','id'=>$admin->idadministrativo));
			}
		}
	
		$this->render('crearAdministrativo',array(
					'model'=>$model,
					'admin'=>$admin,
		));
	}
	
	public function actionCrearProfesor()
	{
		$model=new User;
		$profe=new Profesor;
	
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
	
		if(isset($_POST['User'],$_POST['Profesor']))
		{
			$model->attributes=$_POST['User'];
			$profe->attributes=$_POST['Profesor'];
			$model->foto=CUploadedFile::getInstance($model, 'foto');
			$modeloValido=$model->validate();
			$modeloProfesor=$profe->validate();
			if($modeloValido && $modeloProfesor){
				$model->password=md5($model->password);
				if(isset($model->foto) && $model->foto->error==0){
					$foto_src='/images/user'.'/'.$model->username.'/'.$model->username.'.'.$model->foto->extensionName;
					$model->setAttribute('foto_src', $foto_src);
				}
				$model->save(false);
				if(isset($model->foto) && $model->foto->error==0){
					$carpeta=Yii::getPathOfAlias('webroot.images.user');
					if(!is_dir($carpeta.'/'.$model->username)){
						mkdir($carpeta.'/'.$model->username);
					}
					$carpeta=$carpeta.'/'.$model->username;
					$model->foto->saveAs($carpeta.'/'.$model->username.'.'.$model->foto->extensionName);
				}
				$profe->user_id=$model->id;
				$profe->save(false);
				Rights::assign('Profesor', $model->id);
				$this->redirect(array('verProfesor','id'=>$profe->idprofesor));
			}
		}
	
		$this->render('crearProfesor',array(
						'model'=>$model,
						'profe'=>$profe,
		));
	}
	
	public function actionCreate()
	{
		$model=new User;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			
			if($model->save()){
				$model->password=md5($model->password);
				$this->redirect(array('view','id'=>$model->id));
			}
				
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			$model->password=md5($model->password);
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$model = $this->loadModel($id);
			$model->activo=0;
			$model->save();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Solicitud inválida. Por favor, no repita esta solicitud de nuevo.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('User',array(
    		'criteria'=>array(
        		'condition'=>'activo=1',//condicionamos solo mostrar los usuarios Activos
    			),
    		'pagination'=>array( //el tamaño del CActiveData... 
        	'pageSize'=>20,
    		),
		));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		$model->findAll();
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'La página solicitada no existe.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
			{
				echo CActiveForm::validate($model);
				Yii::app()->end();
			}
	}
	
	//-----------------------pdf individual
	public function actionPdf($id)
	{
		if($id!=null){
			$this->render('pdf',array('model'=>$this->loadModel($id),));
		}
		else
			throw new CHttpException(404,'La solicitud no es válida..');
	}
	
	//-----------------------pdf de una lista
	public function actionListaUsuarioPdf()
	{
		$dataProvider = $_SESSION['datos_filtrados']->getData();
		if($dataProvider!=null){
			$this->render('listaUsuarioPdf',array(
		 		'dataProvider'=>$dataProvider,));
		}
		else
		throw new CHttpException(404,'La solicitud no es válida..');
	}
	
	public function actionListaProfesorPdf()
	{
		$dataProvider = $_SESSION['datos_filtrados']->getData();
		if($dataProvider!=null){
			$this->render('listaProfesoresPdf',array(
		 		'dataProvider'=>$dataProvider,));
		}
		else
			throw new CHttpException(404,'La solicitud no es válida..');
	}
	
	public function actionListaAdminPdf()
	{
		$dataProvider = $_SESSION['datos_filtrados']->getData();
		if($dataProvider!=null){
			$this->render('listaAdministradorPdf',array(
				'dataProvider'=>$dataProvider,));
		}
		else
			throw new CHttpException(404,'La solicitud no es válida..');
	}
	
	public function actionListaAdminisPdf()
	{
		$dataProvider = $_SESSION['datos_filtrados']->getData();
		if($dataProvider!=null){
			$this->render('listaAdministrativoPdf',array(
				 'dataProvider'=>$dataProvider,));
		}
		else
			throw new CHttpException(404,'La solicitud no es válida..');
	}
}
